<template>
  <div class="m-info-content">
    <w-form-validate @on-validate="onSaveOrUpdate">
      <div class="info">
        <span class="title">热点分类</span>
        <div class="type">
          <w-select :disabled="disabled" :options="hotOptions" v-model="params.typeId" @on-all="onSelectType"></w-select>
        </div>
        <span class="c-main tip">头条时不选</span>
      </div>
      <div class="info">
        <span class="title">内容类型</span>
        <div class="type">
          <w-select :options="typeOptions" v-model="params.docType" @on-select="onSelectDoc"></w-select>
        </div>
      </div>
      <div class="info">
        <span class="title">主标题</span>
        <div class="type">
          <w-input holder="请输入" rule="isEmpty" error="请输入" v-model="params.title"></w-input>
        </div>
      </div>
      <div class="info">
        <span class="title">子标题</span>
        <div class="type">
          <w-input holder="请输入" rule="isEmpty" error="请输入" v-model="params.subtitle"></w-input>
        </div>
      </div>
      <!-- 上传图片 -->
      <div class="info">
        <span class="title" style="vertical-align: top;">封面图片</span>
        <div class="imgs">
          <div class="img">
            <img v-lazy="`${params.coverPath}`" alt="封面图片">
          </div>
          <div class="upload cur">
            浏览
            <input type="file" accept="image/png,image/jpg,image/jpeg,image/gif" @change="onUploadImg">
          </div>
        </div>
      </div>
      <div class="info">
        <span class="title">排序</span>
        <div class="type">
          <w-input holder="请输入" rule="isEmpty|onlyInt" error="请输入|请输入数字" v-model="params.sequence"></w-input>
        </div>
      </div>
      <div class="info">
        <span class="title" style="vertical-align: top;">内容</span>
        <div class="editor">
          <quill-editor class="m-editor" :options="editorOption" ref="quillEditor" v-model="params.hotspotInfo"></quill-editor>
          <!-- 文件上传 -->
          <form id="imgForm">
            <input type="file" id="quill-editor-file" style="display: none;" @change="emitImgUpload($event.target.files[0], $refs.quillEditor.quill)">
          </form>
          <!-- <input type="file" id="quill-editor-file" style="display: none;" accept="image/jpg,image/jpeg,image/png,image/gif" @change="emitImgUpload($event.target.files[0], $refs.quillEditor.quill)"> -->
        </div>
      </div>
      <div class="m-btns">
        <button type="submit" class="btn">提交</button>
        <button class="btn colse" @click="$router.go(-1)">取消</button>
      </div>
    </w-form-validate>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { apiHotNewMange, apiShopMange } from 'js/api'
import { session } from 'js/util'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      disabled: false, // 禁用
      // 热点类型
      hotOptions: [],
      typeOptions: [
        {label: 'top', value: 'top'},
        {label: 'hot', value: 'hot'}
      ],
      // 自定义富文本toolbar
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{'header': 1}, {'header': 2}],
            [{'indent': '-1'}, {'indent': '+1'}],
            [{'script': 'sub'}, {'script': 'super'}],
            [{'size': ['normal', 'small', false, 'large', 'huge']}],
            [{'align': []}],
            [{'font': []}],
            [{'list': 'ordered'}, {'list': 'bullet'}],
            [{'header': [1, 2, 3, 4, 5, 6, false]}],
            [{'color': []}, {'background': []}],
            ['image', 'link']
          ]
        }
      },
      params: {
        id: this.$route.query.hotid || '',
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        docType: '',
        title: '',
        subtitle: '',
        sequence: '',
        coverPath: '',
        hotspotInfo: '',
        // 头条
        typeName: null,
        typeId: null
      }
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  created() {
    apiShopMange.apiShopType('热点分类').then(data => {
      const list = data.data || []
      if (list && list.length) {
        this.hotOptions = list.map(item => {
          return {
            label: item.dictName,
            value: item.id
          }
        })
        this.$nextTick(() => {
          if (this.$route.query.hotid) {
            this.params = Object.assign({}, this.params, session.get('hotNewsInfo'))
            // 查看详情
            apiHotNewMange.apiHotNewsInfo(this.token, this.$route.query.hotid).then(data => {
              this.params.hotspotInfo = data.data
            })
          }
        })
      }
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.quillEditor.quill.getModule('toolbar').addHandler('image', () => {
        document.querySelector('#quill-editor-file').click()
      })
    })
  },
  methods: {
    /**
     * 选择分类
     */
    onSelectDoc(type) {
      if (this.params.docType == 'top') {
        this.disabled = true
        this.params.typeId = ''
        this.params.typeName = ''
      } else {
        this.disabled = false
      }
    },
    onSelectType(type) {
      this.params.typeName = type.label
    },
    /**
     * 上传封面图片
     */
    onUploadImg(ev) {
      const oFile = ev.target.files[0]
      const formData = new FormData()
      if (!oFile) {
        return
      }
      // if (oFile.size > 1048576) {
      //   this.$toast('请选择小于1M的图片')
      //   return
      // }
      if (!/\.(png|jpeg|jpg|gif)/i.test(oFile.name)) {
        this.$toast('请选择JPG,JPEG,PNG,GIF格式的图片')
        return
      }
      formData.append('file', oFile)
      formData.append('type', 'hotortop')
      apiHotNewMange.apiHotNewsUpload(formData).then(data => {
        this.params.coverPath = data.data.filePath || ''
        // this.params.filePath = data.data.filePath
      })
    },
    // 文本域图片上传
    emitImgUpload(file, Editor) {
      const formData = new FormData()
      if (!file) {
        return
      }
      // if (file.size > 1048576) {
      //   this.$toast('请选择小于1M的图片')
      //   return
      // }
      if (!/\.(png|jpeg|jpg|gif)/i.test(file.name)) {
        this.$toast('请选择JPG,JPEG,PNG,GIF格式的图片')
        return
      }
      formData.append('file', file)
      formData.append('type', 'hotortop')
      apiHotNewMange.apiHotNewsUpload(formData).then(data => {
        const path = data.data.filePath
        Editor.insertEmbed(Editor.getSelection().index, 'image', path)
        // 重置表单,清空input的内容
        document.querySelector('#imgForm').reset()
      })
    },
    /**
     * 新增，修改
     */
    onSaveOrUpdate() {
      this.params.accessToken = this.token
      if (!this.params.coverPath) {
        this.$toast('请上传封面图片')
        return
      }
      if (!this.params.hotspotInfo) {
        this.$toast('请填写新闻内容')
        return
      }
      apiHotNewMange.apiHotNewsUpdate(this.params).then(data => {
        this.$toast('操作成功', () => {
          this.$router.push(`list?three=${this.$route.query.three}`)
        })
      })
    }
  },
  components: {
    'quill-editor': quillEditor
  }
}
</script>

<style lang="scss">
.m-info-content {
  .editor {
    .ql-container {
      em {
        font-style: italic;
      }
      strong, b {
        font-weight: bold
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.m-info-content {
  margin: 20px auto 10px 300px;
  .info {
    margin-bottom: 20px;
    .title {
      width: 60px;
      display: inline-block;
      text-align: right;
      margin-right: 20px;
    }
    .type {
      width: 230px;
      display: inline-block;
    }
    .tip {
      margin-left: 20px;
    }
    .imgs {
      display: inline-block;
      .img {
        display: inline-block;
        width: 54px;
        height: 54px;
        margin-right: 20px;
      }
      .upload {
        position: relative;
        display: inline-block;
        width:60px;
        height:28px;  
        color: #3693FF;
        border: 1px solid;
        text-align: center;
        line-height: 28px;
        vertical-align: top;
      }
      input {
        position: absolute;
        left: 0;
        width: 100%;
        overflow: hidden;
        opacity: 0;
      }
    }
    .editor {
      display: inline-block;
      width: 540px;
      .m-editor {
        height: 370px;
      }
    }
  }
  .m-btns {
    margin: 76px auto 10px 200px;
  }
}
</style>
